package com.zsck.pos.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewStub;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.chinaums.commoncheck.R;
import com.zsck.pos.adapter.BillAdapter;
import com.zsck.pos.adapter.ProjectAdapter;
import com.zsck.pos.adapter.RecordAdapter;
import com.zsck.pos.base.BaseTitleActivity;
import com.zsck.pos.bean.Project;
import com.zsck.pos.bean.Record;
import com.zsck.pos.bean.Records;
import com.zsck.pos.net.MyObserver;
import com.zsck.pos.net.NetConfig;
import com.zsck.pos.net.RetrofitCilent;
import com.zsck.pos.utils.KeyBoardUtils;
import com.zsck.pos.utils.LogUtil;
import com.zsck.pos.utils.SharePreferenceUtils;
import com.zsck.pos.view.RefreshListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.zsck.net.Utils.RxHelper.observableIO2Main;

public class RecordsActivity extends BaseTitleActivity implements AdapterView.OnItemClickListener, TextWatcher, TextView.OnEditorActionListener, RefreshListView.OnRefreshListener, AdapterView.OnItemSelectedListener {

    /*下拉选择*/
    @BindView(R.id.sp_project)
    Spinner mSpProject;
    /*搜索框*/
    @BindView(R.id.et_search)
    EditText mEtSearch;
    /*删除*/
    @BindView(R.id.iv_delete)
    ImageView mIvDelete;
    /*删除*/
    @BindView(R.id.lv_list)
    RefreshListView mLvList;
    /*空*/
    @BindView(R.id.ll_empty)
    LinearLayout mLlEmpty;

    private int page = 1;

    private List<Record> mListData = new ArrayList<>();

    private String mCondition;

    private RecordAdapter adapter;

    private boolean hasMore = true;

    private Project mProject;


    @Override
    public int setLayout() {
        return R.layout.activity_records;
    }

    @Override
    public String setTitle() {
        return "收款记录";
    }

    @Override
    public Activity setActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initEvents();
        initData();
    }


    private void initEvents() {
        mIvDelete.setOnClickListener(this);
        mLvList.setOnItemClickListener(this);
        mEtSearch.setOnEditorActionListener(this);
        mEtSearch.addTextChangedListener(this);
        mLvList.setOnRefreshListener(this);

        mSpProject.setOnItemSelectedListener(this);
    }

    private void initData() {
        adapter = new RecordAdapter(this, mListData);
        mLvList.setAdapter(adapter);
        mLvList.addHeaderView(new ViewStub(this));
        mLvList.addFooterView(new ViewStub(this));
//        if(NetConfig.projects == null){
//        getProjectAppSelectList();
//        }else{
//            initSpinner();
//            getPageBillList();
//        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        getProjectAppSelectList();
    }

    private void getProjectAppSelectList() {
        String possn = SharePreferenceUtils.getString(this, "POSSN");
        Map<String, Object> map = new HashMap<>();
        if (!TextUtils.isEmpty(possn)) {
            map.put("posId", possn);
        }

        MyObserver<List<Project>> observer = new MyObserver<List<Project>>(this) {
            @Override
            public void onSuccess(List<Project> result) {
                if(result!=null&&result.size()>0){
                    NetConfig.projects = result;
                    initSpinner();
                    getPageBillList();
                }else{
                    mLvList.setVisibility(View.GONE);
                    mLlEmpty.setVisibility(View.VISIBLE);
                    Toast.makeText(RecordsActivity.this,"没有项目权限",Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LogUtil.e("test", e.getMessage());
            }

            @Override
            public void reRequest() {
                getProjectAppSelectList();
            }
        };
        /*RetrofitCilent.getApiService().getProjectAppSelectList(map).
                compose(observableIO2Main(this)).subscribe(observer);*/
        RetrofitCilent.getApiService().queryProject(map).
                compose(observableIO2Main(this)).subscribe(observer);
    }


    private void initSpinner() {
        if (NetConfig.projects == null || NetConfig.projects.size() == 0) {
            return;

        }
        mProject = NetConfig.projects.get(0);
//        ArrayAdapter<Project> adapter = new ArrayAdapter<Project>(this, R.layout.spinner_item, NetConfig.projects);
        ProjectAdapter adapter = new ProjectAdapter(this, NetConfig.projects);
//        adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);

        mSpProject.setAdapter(adapter);

        String projectId = SharePreferenceUtils.getString(this, "projectId");
        if (TextUtils.isEmpty(projectId)) {
            return;
        }
        for (int i = 0; i < NetConfig.projects.size(); i++) {
            Project project = NetConfig.projects.get(i);
            if (projectId.equals(project.getId())) {
                mProject = project;
                mSpProject.setSelection(i);
                break;
            }
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        page = 1;
        getPageBillList();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_delete:
                mEtSearch.setText(null);
                break;
            case R.id.btn_records:

                break;
        }
    }


    private void getPageBillList() {
        Map<String, Object> map = new HashMap<>();
        if (mProject == null) {
            Toast.makeText(RecordsActivity.this,"无项目权限，无法查询账单",Toast.LENGTH_SHORT).show();
            return;
        }
        map.put("projectId", mProject.getId());
        map.put("condition", mCondition);
        map.put("currentPage", page);
        map.put("pageSize", 10);
        MyObserver<Records> observer = new MyObserver<Records>(this) {
            @Override
            public void onSuccess(Records result) {
                onBillList(result);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                LogUtil.e("test", e.getMessage());
                Toast.makeText(RecordsActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void reRequest() {
                getPageBillList();
            }
        };
        RetrofitCilent.getApiService().getPageGetinList(map).
                compose(observableIO2Main(this)).subscribe(observer);
    }


    private void onBillList(Records result) {
        mLvList.refreshComplete(true);
        if (page == 1) {
            if (result == null || result.getRows() == null || result.getRows().size() == 0) {
                mLvList.setVisibility(View.GONE);
                mLlEmpty.setVisibility(View.VISIBLE);
                hasMore = false;
                return;
            }
        } else if (result == null || result.getRows() == null || result.getRows().size() < 10) {
            hasMore = false;
        }
        mLvList.setVisibility(View.VISIBLE);
        mLlEmpty.setVisibility(View.GONE);
        if (page == 1) {
            mListData.clear();
        }
        mListData.addAll(result.getRows());
        adapter.notifyDataSetChanged();
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent();
        ComponentName componentName = new ComponentName("com.ums.sz.pos", "com.zsck.pos.activity.RecordActivity");
        intent.putExtra("batchNo", mListData.get(position).getBatchNo());
        intent.setComponent(componentName);
        startActivity(intent);
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        mIvDelete.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            mCondition = mEtSearch.getText().toString();
            page = 1;
            hasMore = true;
            getPageBillList();
            KeyBoardUtils.hideByView(this, mEtSearch);
        }
        return false;
    }

    @Override
    public void onLoadMore() {
        if (!hasMore) {
            return;
        }
        page++;
        getPageBillList();
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        page = 1;
        mProject = NetConfig.projects.get(position);
        SharePreferenceUtils.putString(this, "projectId", mProject.getId());
        getPageBillList();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}
